package com.lionel.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
@Slf4j
public class SemaphoreExample1 {
    /**
     * 每一秒并发的请求是3个
     */
    private final static int threadCount = 20;
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0;i<threadCount;i++){
            int threadNum = i;
            exec.execute(()->{
                try {
                    //获得一个许可
                    semaphore.acquire();
                    test(threadNum);
                    //释放一个许可
                    semaphore.release();

                } catch (Exception e) {
                    log.error("exception",e);
                }
            });
        }
        exec.shutdown();

    }
    private static void test(int threadNum) throws Exception {
        log.info("{}",threadNum);
        Thread.sleep(1000);
    }
}
